package com.gitee.funcy.disruptorlearn.ch04;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author fangchengyan
 * @date 2019-03-13 16:36
 */
public class JcuReview {

    public static void main(String[] args) {

        /**
         * 线程池最佳实践：自主定义 ThreadPoolExecutor
         * 1. 线程的数量
         * 2. 任务队列的容量
         * 3. 设置线程属性
         * 4. 拒绝策略
         *
         *
         */

        ExecutorService service = new ThreadPoolExecutor(
                // 设置线程数时，需要注意任务的类型是io密集型还是计算密集型，再进行合理设置
                Runtime.getRuntime().availableProcessors(),
                Runtime.getRuntime().availableProcessors(),
                0L,
                TimeUnit.MILLISECONDS,

                // 这里设置任务队列的最大容量
                new LinkedBlockingQueue<>(200),

                new ThreadFactory() {
                    /**
                     * 可以在该方法中设置线程池名称等
                     * @param r
                     * @return
                     */
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("myThreadPool-");
                        return thread;
                    }
                },
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        System.err.println("拒绝策略：" + r);
                    }
                }
        );
    }

}
